<template>
    <div class="app-container">
        <el-form ref="searchForm" inline :model="searchForm" style="position:relative;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="所属栏目：" prop="columnId">
                        <el-cascader clearable :options="parentOpt" :props="optionProps" v-model="searchForm.columnId" change-on-select></el-cascader>
                    </el-form-item>
                    <el-form-item label="标题：" prop="title">
                        <el-input clearable v-model="searchForm.title" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="文件类型：" prop="fileType">
                        <el-select clearable v-model="searchForm.fileType" placeholder="请选择">
                            <el-option v-for="item in fileTypeOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button @click="init('search')" type="primary">查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick" type="primary" style="position: absolute;right: 0;">添加</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin: 20px 0px;">
            <el-table-column prop="parentList" :formatter="parentListFun" label="所属栏目" align="center"></el-table-column>
            <el-table-column prop="title" label="标题" align="center"></el-table-column>
            <el-table-column prop="fileType" :formatter="fileTypeFun" label="文件类型" align="center"></el-table-column>
            <el-table-column prop="sort" label="顺序值" align="center"></el-table-column>
            <el-table-column prop="usingStatus" :formatter="usingStatusFun" label="可用性" align="center"></el-table-column>
            <el-table-column label="操作" width="220" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button @click.stop="editClick(scope.row)" :disabled="(scope.row.usingStatus != 1)" type="primary" plain size="mini">编辑</el-button>
                    <el-button @click.stop="statusClick(scope.row)" type="warning" plain size="mini">{{(scope.row.usingStatus == 1) ? '禁用' : '启用'}}</el-button>
                    <el-button @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="所属栏目：" prop="columnId">
                    <el-cascader :options="parentOpt" :props="optionProps" v-model="columnId" change-on-select style="width: 100%;" placeholder="必选项。请选择所属栏目"></el-cascader>
                </el-form-item>
                <el-form-item label="标题：" prop="title">
                    <el-input v-model="dataForm.title" placeholder="必填项。请输入标题，长度为1-30位" maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="文件类型：" prop="fileType">
                    <el-select v-model="dataForm.fileType" placeholder="请选择文件类型" style="width: 100%;">
                        <el-option v-for="item in fileTypeOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="顺序值：" prop="sort">
                    <el-input v-model="dataForm.sort" type="number" placeholder="请输入顺序值"></el-input>
                </el-form-item>
                <el-form-item label="可用性：" prop="usingStatus">
                    <el-select v-model="dataForm.usingStatus" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="item in usingStatusOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { creatTag, findTag, updateTag, releaseTag, delTag } from '@/api/content/tag'
import { findColumn } from '@/api/content/column'
import { isvalidInitNumber } from '@/utils/validate'
export default {
    name: 'Tag',
    data() {
        var InitNumber=(rule, value,callback)=>{
            if(value){
                if(isvalidInitNumber(value)){
                    callback()
                }else{
                    callback(new Error('请输入整数'))
                }
            }else{
                callback()
            }
        }
        return{
            tableData: [],
            nowTit: '',
            nowId: '',
            showDialog: false,
            dataForm: {
                columnId: [],
                fileType: 1,
                sort: '',
                title: '',
                usingStatus: 1,
            },
            rules: {
                title: [
                    { required: true, message: '请输入', trigger: 'blur' }
                ],
                sort: [
                    { trigger: 'blur', validator: InitNumber }
                ],
            },
            searchForm: {
                columnId: [],
                title: '',
                fileType: ''
            },
            columnId: [],
            nowPage: 0,
            pageSize: 10,
            imageUrl: '',
            formData: {},
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            parentOpt: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
            fileTypeOpt: [
                {label: '图片', value: 1},
                {label: '视频', value: 2},
                {label: '图文', value: 3}
            ],
            usingStatusOpt: [
                {label: '启用', value: 1},
                {label: '禁用', value: 0}
            ],
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            let cid = '';
            if(this.searchForm.columnId.length != 0){
                cid = this.searchForm.columnId[this.searchForm.columnId.length - 1];
            }
            //获取列表信息
            findTag({ columnId: cid, title: this.searchForm.title, fileType: this.searchForm.fileType, page: this.nowPage, size: this.pageSize }).then(response => {
                if(response.code == 200){
                    if(response.object){
                        _this.pageData = response.object;
                        if(response.object.content){
                            _this.tableData = response.object.content;
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        columnOpt(){
            const _this = this;
            //获取列表信息
            findColumn( '', '', '', 0, 1000).then(response => {
                if(response.code == 200){
                    if(response.object){
                        if(response.object.content){
                            const arr = response.object.content;
                            _this.parentOpt = _this.getTreeData(arr);
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if(data[i].children.length<1){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        //添加
        addClick(){
            this.popStatus = 0;
            this.showDialog = true;
            this.dataForm.columnId = '';
            this.columnId = [];
            this.dataForm.fileType = 1;
            this.dataForm.sort = '';
            this.dataForm.title = '';
            this.dataForm.usingStatus = 1;
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //其他的表单校验
        otherValidate(){
            if(!this.dataForm.columnId){
                this.$message.warning('请选择所属栏目');
                return false
            }
            return true
        },
        //提交添加
        addSubmit(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    _this.dataForm.columnId = this.columnId[this.columnId.length - 1];
                    //表单校验
                    _this.otherValidate();
                    if(!_this.otherValidate()){
                        return
                    }
                    if(_this.popStatus == 0){  //添加
                        creatTag(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })

                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        updateTag(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                    
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.title+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delTag({id:row.id}).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            this.dataForm.columnId = row.columnId;
            //处理所属项目id
            if(row.parentList){
                let arr = [];
                for (const key in row.parentList) {
                    if (row.parentList.hasOwnProperty(key)) {
                        const element = row.parentList[key];
                        arr.push(element.id);
                    }
                }
                this.columnId = arr;
            }
            this.dataForm.fileType = row.fileType;
            this.dataForm.sort = row.sort;
            this.dataForm.title = row.title;
            this.dataForm.usingStatus = row.usingStatus;
            this.showDialog = true;
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.$refs[formName].resetFields();
        },
        //启用禁用
        statusClick(row){
            let usingStatus,isUsing;
            if(row.usingStatus == 1){  //启用状态
                usingStatus = 0;
                isUsing = '禁用';
            }else{
                usingStatus = 1;
                isUsing = '启用';
            }

            let _this = this;
            this.$confirm('确定修改状态为 '+ isUsing +' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //启用禁用
                releaseTag({id: row.id, usingStatus: usingStatus}).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        usingStatusFun(row){
            if(row.usingStatus == 1){
                return '启用'
            }else if(row.usingStatus == 0){
                return '禁用'
            }
        },
        parentListFun(row){
            let str = '';
            if(row.parentList){
                for (const key in row.parentList) {
                    if (row.parentList.hasOwnProperty(key)) {
                        const element = row.parentList[key];
                        str += element.name + ' / ';
                    }
                }
            }
            return str.substr(0,str.length-3)
        },
        fileTypeFun(row){
            if(row.fileType == 1){
                return '图片'
            }else if(row.fileType == 2){
                return '视频'
            }else if(row.fileType == 3){
                return '图文'
            }
        },
    },
    mounted(){
        this.init();
        this.columnOpt();
    }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>